"use strict";
const path = require("path");
// 删除无用代码
const TerserPlugin = require("terser-webpack-plugin");
function resolve(dir) {
  return path.join(__dirname, dir);
}

// 性能分析
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const CompressionPlugin = require("compression-webpack-plugin");

const name = process.env.VUE_APP_TITLE || "智慧能耗管理系统"; // 网页标题

const port = process.env.port || process.env.npm_config_port || 8888; // 端口

// 获取GIT版本
const GitRevisionPlugin = require("git-revision-webpack-plugin");

const gitRevision = new GitRevisionPlugin();

const Timestamp = new Date().getTime()

// const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')

process.env.VUE_APP_BUILD_DATE = JSON.stringify(new Date().toLocaleString());
process.env.VUE_APP_BRANCH = JSON.stringify(gitRevision.branch());
process.env.VUE_APP_COMMITHASH = JSON.stringify(gitRevision.commithash());
process.env.VUE_APP_VERSION = JSON.stringify(gitRevision.version());

// vue.config.js 配置说明
//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分，具体配置参考文档
module.exports = {
  // 部署生产环境和开发环境下的URL。
  // 默认情况下，Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
  // 在npm run build 或 yarn build 时 ，生成文件的目录名称（要和baseUrl的生产环境路径一致）（默认dist）
  outputDir: "dist",
  // 用于放置生成的静态资源 (js、css、img、fonts) 的；（项目打包之后，静态资源会放在这个文件夹下）
  assetsDir: "static",
  // 是否开启eslint保存检测，有效值：ture | false | 'error'
  lintOnSave: process.env.NODE_ENV === "development",
  // 如果你不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    host: "0.0.0.0",
    port: port,
    open: true,
    proxy: {
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
        // target: "http://192.168.1.44:8080/", // 开发环境
        target: "http://192.168.1.44:28080", // 测试环境(test)
        // target: "http://192.168.1.212:8080/", // 杜
        // target: "http://192.168.1.174:8080/", // 熊
        // target: "http://nddns.neusense.info:48080/", // 外部测试环境
        // target:'http://prod.skst.tetpark.com', // 生产环境
        changeOrigin: true,
        pathRewrite: {
          ["^" + process.env.VUE_APP_BASE_API]: "",
        },
      },
    },
    disableHostCheck: true,
  },
  css: {
    loaderOptions: {
      sass: {
        sassOptions: { outputStyle: "expanded" },
      },
    },
  },
  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        "@": resolve("src"),
      },
    },
    plugins: [
      new CompressionPlugin({
        cache: false, // 不启用文件缓存
        test: /\.(js|css|html)?$/i, // 压缩文件格式
        filename: "[path].gz[query]", // 压缩后的文件名
        algorithm: "gzip", // 使用gzip压缩
        minRatio: 0.8, // 压缩率小于1才会压缩
      }),
    ],
  },

  // css-unicode-loader 解决dart-sass编译element-ui打包出来的icon乱码
  configureWebpack: (config) => {
    config.module.rules
      .filter((rule) => {
        return rule.test.toString().indexOf("scss") !== -1;
      })
      .forEach((rule) => {
        rule.oneOf.forEach((oneOfRule) => {
          oneOfRule.use.splice(
            oneOfRule.use.indexOf(require.resolve("sass-loader")),
            0,
            { loader: require.resolve("css-unicode-loader") }
          );
        });
      });

    // plugins: [new HardSourceWebpackPlugin({
    //   cacheDirectory: 'node_modules/.cache/hard-source/[confighash]',
    //   recordsPath: 'node_modules/.cache/hard-source/[confighash]/records.json',
    //   configHash: function (webpackConfig) {
    //     // node-object-hash on npm can be used to build this.
    //     return require('node-object-hash')({ sort: false }).hash(webpackConfig);
    //   },
    //   environmentHash: {
    //     root: process.cwd(),
    //     directories: [],
    //     files: ['package-lock.json'],
    //   },
    // })]

    if (process.env.NODE_ENV === "production") {
      config["performance"] = {
        maxEntrypointSize: 10000000,
        maxAssetSize: 30000000,
      };
    }
  },
  chainWebpack(config) {
    config.externals({ './cptable': 'var cptable' })
    if (process.env.NODE_ENV === 'production') {
      // 给js和css配置Timestamp
      config.output.filename('static/js/[name].' + Timestamp + '.js').end()
      config.output.chunkFilename('static/js/[name].' + Timestamp + '.js').end()
      config.plugin('extract-css').tap(args => [{
        filename: `static/css/[name].${Timestamp}.css`,
        chunkFilename: `static/css/[name].${Timestamp}.css`
      }])
      // 给img配置Timestamp
      config.module.rule('images').use('url-loader').tap(options => {
        options.name = `static/img/[name].${Timestamp}.[ext]`
        options.fallback = {
          loader: 'file-loader',
          options: {
            name: `static/img/[name].${Timestamp}.[ext]`
          }
        }
        return options
      })
    }
    // Timestamp 时间设置的一个变量 直接在module.exports 上面 const Timestamp = new Date().getTime()
    config.plugins.delete("preload"); // TODO: need test
    config.plugins.delete("prefetch"); // TODO: need test
    config
      .when(process.env.NODE_ENV === "development", (config) => {
        // 修复HMR
        config.resolve.symlinks(true);
        // 性能分析，默认端口8888
        config.plugin("webpack-bundle-analyzer").use(BundleAnalyzerPlugin);
      })
      .end();
    // set svg-sprite-loader
    config.module.rule("svg").exclude.add(resolve("src/assets/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();

    config.when(process.env.NODE_ENV !== "development", (config) => {
      config
        .plugin("ScriptExtHtmlWebpackPlugin")
        .after("html")
        .use("script-ext-html-webpack-plugin", [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/,
          },
        ])
        .end();
      // 公共代码抽离
      config.optimization
        .splitChunks({
          chunks: "all",
          cacheGroups: {
            libs: {
              name: "chunk-libs",
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: "initial", // only package third parties that are initially dependent
            },
            commons: {
              name: "chunk-avue",
              test: resolve("public/cdn/avue"), // can customize your rules
              minChunks: 3, //  minimum common number
              priority: 5,
              reuseExistingChunk: true,
            },
          },
        })
        .end();
      config.optimization.runtimeChunk("single"),
      {
        from: path.resolve(__dirname, "./public/robots.txt"), //防爬虫文件
        to: "./", //到根目录下
      };
      config.plugin("TerserPlugin").use(
        new TerserPlugin({
          cache: true,
          parallel: true,
          sourceMap: false,
          terserOptions: {
            compress: {
              unused: true, // 删除无用的代码
              dead_code: true, // 移除无用的代码
              drop_console: true,
              drop_debugger: true,
            },
          },
        })
      );
    });
  },
};
